package com.example.module_hp_zao_yin.base;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;

import org.jetbrains.annotations.NotNull;

import java.lang.reflect.ParameterizedType;

public abstract class BaseMvvmFragment<T extends ViewDataBinding,X extends ViewModel> extends Fragment {
    protected Activity mContext;
    protected X viewModel;
    protected View mRootView;
    protected T binding;

    @Override
    public void onAttach(@NotNull Context context) {
        super.onAttach(context);
        this.mContext = (Activity) context;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container
            , Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, initLayout(), container, false);
        mRootView = binding.getRoot();
        Class<X> xClass = (Class<X>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[1];
        viewModel = new ViewModelProvider(this).get(xClass);
        binding.setLifecycleOwner(this);
        binding.setVariable(initBR(),viewModel);
        initView(mRootView, savedInstanceState);
        return mRootView;
    }
    //layout
    protected abstract int initLayout();
    //设置数据id,文件直接return BR.data;
    protected abstract int initBR();
    /**
     * 该抽象方法就是 初始化view
     *
     * @param view
     * @param savedInstanceState
     */
    protected abstract void initView(View view, Bundle savedInstanceState);

    /*公共方法*/
    //Toast弹窗
    public void showToast(String msg) {
        Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
    }
    //Toast异步弹窗
    public void showToastSync(String msg) {
        if(Looper.myLooper()==null){
            Looper.prepare();
        }
        Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
        Looper.loop();
    }
    //Fragment设置跳转
    public void navigateTo(Class cls) {
        Intent in = new Intent(getActivity(), cls);
        startActivity(in);
    }
    //Fragment设置传参跳转
    public void navigateToWithBundle(Class cls, Bundle bundle) {
        Intent in = new Intent(getActivity(), cls);
        in.putExtras(bundle);
        startActivity(in);
    }
    //Fragment设置Flag跳转，清楚栈记录
    public void navigateToWithFlag(Class cls, int flags) {
        Intent in = new Intent(getActivity(), cls);
        in.setFlags(flags);
        startActivity(in);
    }
}
